<template>
  <el-dialog title="非住房帐详细信息" :visible.sync="dialogVisible" append-to-body width="80%">
    <!-- <el-button
      @click="exportExcel()"
      type="primary"
    >导出</el-button> -->
    <el-table :data="dataList" border v-loading="dataListLoading" @selection-change="selectionChangeHandle" id="out-table"
      style="width: 100%;">
      <el-table-column :label="'非房间帐收支表 '+dateFormat('YYYY-mm-dd',times[0])+'~'+dateFormat('YYYY-mm-dd',times[1])"
        header-align="center" align="center">

        <el-table-column :label="'总计：¥ '+(inTotal-outTotal)" header-align="center" align="center">
          <el-table-column prop="number" header-align="center" align="center" fixed label="编号">
          </el-table-column>
          <el-table-column prop="createTime" header-align="center" align="center" label="时间" fixed>
          </el-table-column>
          <el-table-column prop="createAccount" header-align="center" align="center" label="操作人" fixed>
          </el-table-column>
        </el-table-column>
        <el-table-column :label="'收入小计：¥'+inTotal" header-align="center" align="center">
          <el-table-column label="收入" header-align="center" align="center">
            <el-table-column v-for="(name,index) in typesIn" :key="name.id" :label="name.name">
              <template slot-scope="props" v-if="dataList[props.$index]['type']==1">
                {{values[props.$index][index]['value']}}
              </template>
            </el-table-column>
          </el-table-column>
        </el-table-column>
        <el-table-column :label="'支出小计：¥ -'+outTotal" header-align="center" align="center">
          <el-table-column label="支出" header-align="center" align="center">
            <el-table-column v-for="(name,index) in typesOut" :key="name.id" :label="name.name">
              <template slot-scope="props" v-if="dataList[props.$index]['type']==-1">
                -{{values[props.$index][index]['value']}}
              </template>
            </el-table-column>
          </el-table-column>
        </el-table-column>

        <el-table-column fixed header-align="center" align="center" label="小计">
          <template slot-scope="scope">
            {{scope.row.type==-1?'-':''}}{{xiaoji(values[scope.$index],dataList[scope.$index]['type'])}}
          </template>
        </el-table-column>
        <el-table-column fixed prop="paymentMethod" header-align="center" align="center" label="支付方式">

        </el-table-column>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
      :page-sizes="[5,10, 20, 50, 100]" :page-size="pageSize" :total="totalPage" layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
  </el-dialog>
</template>

<script>
  import FileSaver from "file-saver";
  import XLSX from "xlsx";
  import Moment from 'moment'
  export default {
    data() {
      return {
        dataForm: {
          key: ''
        },
        addSum: parseFloat(this.inTotal) - parseFloat(this.outTotal),
        dataList: [],
        typesIn: [],
        typesOut: [],
        values: [], //对应值
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        modifyNoteVisible: false,
        modifyInoutVisible: false,
        inTotal: 0,
        outTotal: 0,
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        times: [],
        dialogVisible: false,
        isDay: '日'

      }
    },
    components: {},
    activated() {

    },
    methods: {
      init(startTime, endTime) {
        this.dialogVisible = true


        this.times[0] = startTime
        this.times[1] = endTime



        this.pageIndex = 1;
        this.getDataList()
      },
      // 获取数据列表
      getDataList() {
        console.log("dates:" + this.times)
        this.dataListLoading = true,
          this.inTotal = 0,
          this.outTotal = 0,
          this.$http({
            url: this.$http.adornUrl('/hotel/nonroominout/list'),
            method: 'get',
            params: this.$http.adornParams({
              'page': this.pageIndex,
              'limit': this.pageSize,
              'key': this.dataForm.key,
              'start_time': this.times[0],
              'end_time': this.times[1]
            })
          }).then(({
            data
          }) => {
            if (data && data.code === 0) {
              console.log(data.page.list)
              this.dataList = data.page.list
              this.totalPage = data.page.totalCount
              this.typesIn = data.typesIn;
              this.typesOut = data.typesOut;
              this.values = data.values;
              this.inTotalSum();
              // console.log("typesout:",data.typesOut)

            } else {
              this.dataList = []
              this.totalPage = 0
            }
            this.dataListLoading = false
          })
      },
      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle(val) {
        this.dataListSelections = val
      },
      xiaoji(arr, type) {
        let sum = 0;
        for (let index in arr) {
          sum += arr[index]['value'];
        }
        return sum
      },
      inTotalSum() {
        console.log("values", this.values)
        for (let i in this.values) {
          for (let j in this.values[i]) {
            if (this.values[i][j]['typeId'] == 1)
              this.inTotal += this.values[i][j]['value'];
            if (this.values[i][j]['typeId'] == -1)
              this.outTotal += this.values[i][j]['value'];
          }
        }
      },
      dateFormat(fmt, date) {

        if (date == null) {
          return
        }
        let ret;
        date = new Date(date)
        const opt = {
          "Y+": date.getFullYear().toString(), // 年
          "m+": (date.getMonth() + 1).toString(), // 月
          "d+": date.getDate().toString(), // 日
          "H+": date.getHours().toString(), // 时
          "M+": date.getMinutes().toString(), // 分
          "S+": date.getSeconds().toString() // 秒
          // 有其他格式化字符需求可以继续添加，必须转化成字符串
        };
        for (let k in opt) {
          ret = new RegExp("(" + k + ")").exec(fmt);
          if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
          };
        };
        return fmt;
      },
      //定义导出Excel表格事件
      exportExcel() {
        /* 从表生成工作簿对象 */
        var wb = XLSX.utils.table_to_book(document.querySelector("#out-table"));

        for (let item in wb['Sheets']['Sheet1']) {
          if (wb['Sheets']['Sheet1'][item].v == "操作" || wb['Sheets']['Sheet1'][item].v == "编辑删除") {
            wb['Sheets']['Sheet1'][item].v = ""
          }
        }

        const ws = wb.Sheets[wb.SheetNames[0]];
        this.deleteCol(ws, 't')
        console.log(ws)

        /* 获取二进制字符串作为输出 */
        var wbout = XLSX.write(wb, {
          bookType: "xlsx",
          bookSST: true,
          type: "array"
        });
        try {
          FileSaver.saveAs(
            //Blob 对象表示一个不可变、原始数据的类文件对象。
            //Blob 表示的不一定是JavaScript原生格式的数据。
            //File 接口基于Blob，继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
            //返回一个新创建的 Blob 对象，其内容由参数中给定的数组串联组成。
            new Blob([wbout], {
              type: "application/octet-stream"
            }),
            //设置导出文件名称
            '非房间帐收支表 ' + this.dateFormat('YYYY-mm-dd', this.times[0]) + '~' + this.dateFormat('YYYY-mm-dd', this.times[
              1]) + '.xlsx'
          );
        } catch (e) {
          if (typeof console !== "undefined") console.log(e, wbout);
        }
        return wbout;
      },
      deleteCol(ws, index) {
        const range = XLSX.utils.decode_range(ws['!ref']);

        for (let col = index; col < range.e.c; col++) {
          for (let row = range.s.r; row <= range.e.r; row++) {
            ws[encodeCell(row, col)] = ws[encodeCell(row, col + 1)];
          }
        }

        range.e.c--;

        ws['!ref'] = XLSX.utils.encode_range(range.s, range.e);
      }
    }
  }
</script>
